<?php
namespace frontend\controllers;

use Yii;
use common\lib\Page;
use common\models\Tags;
use frontend\models\Novels;
use frontend\models\Lists;
use frontend\models\Contents;

class NovelController extends PublicController
{
    public function actionIndex()
    {
        $novelId = intval(Yii::$app->request->get('novelId'));
        $tagId = intval(Yii::$app->request->get('tagId'));
        $type = Tags::find()->where(['tagId' => $tagId])->asArray()->one();
        $novel = Novels::find()->where(['novelId' => $novelId])->asArray()->one();
        $lists = Lists::find()->select('id,title')->where(['novelName' => $novel['novelName']])->asArray()->all();
        $data = [
            'type' => $type,
            'novel' => $novel,
            'data' => $lists,
        ];
        return $this->render('index', $data);
    }
    
    public function actionChapter(){
        $chapterId = intval(Yii::$app->request->get('id'));
        $tagId = intval(Yii::$app->request->get('tagId'));
        $type = Tags::find()->where(['tagId' => $tagId])->asArray()->one();
        $novelId = intval(Yii::$app->request->get('novelId'));
        $novel = Novels::find()->where(['novelId' => $novelId])->asArray()->one();
        $chapter = Lists::find()->where(['id' => $chapterId])->asArray()->one();
        $content = Contents::find()->select('title,content, novelName,author')->where(['novelName' => $chapter['novelName'], 'title' => $chapter['title']])->asArray()->one();
        if(!empty($content)){
            $content['content'] = $this->getContent($content['content']);
        }
        $data = [
            'type' => $type,
            'novel' => $novel,
            'chapter' => $chapter,
            'data' => $content,
        ];
        return $this->render('chapter', $data);
    }
    
    private function getContent($content){
        $data = explode("\n", $content);
        foreach((array)$data as $k => $v){
            $data[$k] = '<p>'.$v.'</p>';
        }
        $data = implode('', $data);
        return $data;
    }
}
